from leapp.actors import Actor
from leapp.models import ActiveKernelModulesFacts
from leapp.tags import ChecksPhaseTag, IPUWorkflowTag
from leapp import reporting
from leapp.reporting import Report, create_report


class CheckExtraModules(Actor):
    """
    Check if any extra modules not signed by redhat or centos.
    
    If the kernel module is not signed by redhat or centos, it may be provided
    by third party or users.
    """

    name = 'check_extramodules'
    consumes = (ActiveKernelModulesFacts,)
    produces = (Report,)
    tags = (ChecksPhaseTag, IPUWorkflowTag)

    def process(self):
        extra_modules = []
        for fact in self.consume(ActiveKernelModulesFacts):
            for active_module in fact.kernel_modules:
                signer = str(active_module.signature)
                if signer.find('CentOS') == -1 and signer.find('Red Hat') == -1:
                    extra_modules.append(active_module.filename)

        if list(extra_modules):
            extra_modules_new_line = '\n'.join(['- ' + p for p in extra_modules])
            create_report([
                        reporting.Title('Found some active modules not signed by redhat or centos'),
                        reporting.Summary(
                            'The following active modules are not signed by redhat or centos, '
                            'please make sure they can be compat with new kernel:\n{}'
                            .format(extra_modules_new_line)
                        ),
                        reporting.Severity(reporting.Severity.HIGH),
                    ])
